package com.kingtao.session;

import io.netty.channel.Channel;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author: kingtao
 * @Date: 2023-08-25-14:26
 * @Description:
 */
public class GroupSessionImpl implements GroupSession {
    private final Map<Integer, Group> groupMap = new ConcurrentHashMap<>();

    @Override
    public Group createGroup(int master, Set<Integer> members) {
        Group group = new Group(master, members);
        return groupMap.putIfAbsent(master, group);
    }

    @Override
    public Group joinMember(int master, int member) {
        return groupMap.computeIfPresent(master, (key, value) -> {
            value.getMembers().add(member);
            return value;
        });
    }

    @Override
    public Group removeMember(int master, int member) {
        return groupMap.computeIfPresent(master, (key, value) -> {
            value.getMembers().remove(member);
            return value;
        });
    }

    @Override
    public Group removeGroup(int master) {
        return groupMap.remove(master);
    }

    @Override
    public Set<Integer> getMembers(int master) {
        return groupMap.getOrDefault(master, Group.EMPTY_GROUP).getMembers();
    }

    @Override
    public List<Channel> getMembersChannel(int master) {
        return getMembers(master).stream()
                .map(member -> SessionFactory.getSession().getChannel(master))
                .filter(Objects::isNull)
                .collect(Collectors.toList());
    }
}
